﻿using LiteDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace AutoGenTool.Core
{
    internal static class Helper
    {
        public static string GetSha256(string filePath)
        {
            byte[] hashBytes;

            using (var sha256 = SHA256.Create())
            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {
                const int bufferSize = 4096;  // 定义每次读取的缓冲区大小，可以根据实际调整
                byte[] buffer = new byte[bufferSize];
                int bytesRead;

                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    sha256.TransformBlock(buffer, 0, bytesRead, buffer, 0);
                }
                sha256.TransformFinalBlock(buffer, 0, 0);
                hashBytes = sha256.Hash;
            }

            string hash = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();
            return hash;
        }

        public static ILiteDatabase CreateOrGetDb(string filePath)
        {

            var db = new LiteDatabase($"Filename={filePath}");
            return db;
        }

        public static void VisitDb(string filePath, Action<ILiteDatabase> doFunc)
        {
            using var db = CreateOrGetDb(filePath);
            doFunc?.Invoke(db);
        }

        public static string GetClearCombine(string rootDir, string path)
        {
            var clearPart = GetClearPart(path);
            return Path.Combine(rootDir, clearPart);
        }

        private static string GetClearPart(string path)
        {
            if (string.IsNullOrWhiteSpace(path)) return string.Empty;
            if (path.StartsWith("./")) return path.Substring(2);
            if (path.StartsWith(".\\")) return path.Substring(2);
            if (path.StartsWith("/")) return path.Substring(1);
            if (path.StartsWith("\\")) return path.Substring(1);
            if (path.StartsWith("..")) throw new Exception("Helper.GetClearPart: 暂时不支持 .. 返回上上目录的操作");
            return path;
        }

        ///<summary>忽略正反斜杠。</summary>
        public static bool IsPathPrefixEqual(string prefix, string fullpath)
        {
            prefix = TrimSlash(prefix);
            fullpath = TrimSlash(fullpath);

            if (fullpath.Length < prefix.Length)
            {
                return false;
            }
            var validPrefixLen = prefix.Length;

            if (IsSlash(prefix.Last()))
            {
                validPrefixLen = validPrefixLen - 1;
            }

            var len = Math.Min(validPrefixLen, fullpath.Length);

            for (int i = 0; i < len; i++)
            {
                var c1 = GetUniChar(prefix[i]);
                var c2 = GetUniChar(prefix[i]);

                if (c1 != c2) return false;
            }

            if (fullpath.Length == len) return true;
            if (fullpath.Length > len)
            {
                return IsSlash(fullpath[len]);
            }
            else
            {
                return false;
            }

        }

        private static bool IsSlash(char c)
        {
            return c == '/' || c == '\\';
        }

        private static char GetUniChar(char c)
        {
            if (IsSlash(c)) return '/';
            return c;
        }

        private static string TrimSlash(string str)
        {
            return str.TrimEnd('\\').TrimEnd('/');
        }
    }
}
